package com.aek.ebey.sys.service.impl;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aek.common.core.config.RedisRepository;
import com.aek.common.core.exception.ExceptionFactory;
import com.aek.common.core.sms.Sms;
import com.aek.common.core.sms.SmsResult;
import com.aek.ebey.sys.core.SysConstants;
import com.aek.ebey.sys.model.SysUser;
import com.aek.ebey.sys.model.bo.SmsCode;
import com.aek.ebey.sys.service.IndexService;
import com.aek.ebey.sys.service.SysUserService;
import com.alibaba.fastjson.JSON;

@Service
public class IndexServiceImpl implements IndexService {

	@Autowired
	private SysUserService userService;

	@Autowired
	private Sms sms;
	@Autowired
	private RedisRepository redisRepository;

	@Override
	public SmsResult sendCode(String mobile) {

		SysUser user = this.userService.findByMobile(mobile);

		if (user == null) {
			throw ExceptionFactory.create("U_009");
		}

		Date currTime = new Date();
		String key = SysConstants.SYS_GET_PASSWORD_CODE + mobile;

		// 查询是否在1分钟内发送过验证码，则不发送返回1分钟重试
		String smsVlue = this.redisRepository.get(key);
		if (StringUtils.isNotBlank(smsVlue)) {
			SmsCode currSmsCode = JSON.parseObject(smsVlue, SmsCode.class);
			Long date = currTime.getTime() - currSmsCode.getSendTime().getTime();

			if ((date / 60000) < 1) {
				throw ExceptionFactory.create("U_019");
			}
		}

		String code = this.sms.randomCode(6);
		SmsResult result = this.sms.sendCode(mobile, code);
		
		// 发送失败
		if (result.getSuccess() != 1) {
			return result;
		}

		// 过期时间
		long expireTime = 30 * 60;
		SmsCode smsCode = new SmsCode();
		smsCode.setCode(code);
		smsCode.setSendTime(currTime);

		// 保存验证码
		String value = JSON.toJSONString(smsCode);
		this.redisRepository.setExpire(key, value, expireTime);
		return result;
	}

	@Override
	public boolean resetPassword(String mobile, String code, String password) {

		SysUser user = this.userService.findByMobile(mobile);

		if (user == null) {
			throw ExceptionFactory.create("U_009");
		}

		String key = SysConstants.SYS_GET_PASSWORD_CODE + mobile;

		// 查询验证码是否在30分钟有效期内，否则重试
		String smsVlue = this.redisRepository.get(key);

		if (StringUtils.isNotBlank(smsVlue)) {
			SmsCode currSmsCode = JSON.parseObject(smsVlue, SmsCode.class);

			// 判断验证码是否正确
			if (!currSmsCode.getCode().equals(code)) {
				throw ExceptionFactory.create("U_021");
			}

			// 判断密码是否为空
			if (StringUtils.isEmpty(password)) {
				throw ExceptionFactory.create("U_004");
			}

		} else {
			// 缓存验证码不存在，提示重新发送
			throw ExceptionFactory.create("U_020");
		}

		boolean flag = false;
		user.setPassword(this.userService.encrypt(password));
		if (this.userService.updateById(user)) {
			this.redisRepository.del(key);
			flag = true;
		}
		return flag;

	}

}
